<template>
  <PublicPage>
    <view class="px-6 mt-[72rpx]">
      <u-form
        labelPosition="left"
        labelWidth="100"
        :model="formData" 
        :rules="rules"
        ref="form"
        errorType="border-bottom">
        <u-form-item label="旧密码" prop="oldPassword" required>
          <u-input
            v-model="formData.oldPassword"
            border="none"
            inputAlign="right"
            placeholder="请输入旧密码"></u-input>
        </u-form-item>
        <u-form-item label="新密码" prop="newPassword" required>
          <u-input
            v-model="formData.newPassword"
            border="none"
            type="password"
            inputAlign="right"
            placeholder="请输入新密码"></u-input>
        </u-form-item>
        <u-form-item
          label="确认新密码"
          prop="confirmPassword"
          required>
          <u-input
            v-model="formData.confirmPassword"
            border="none"
            type="password"
            inputAlign="right"
            placeholder="请再次输入新密码"></u-input>
        </u-form-item>
      </u-form>
      <view class="mt-10">
        <u-button type="primary" @click="confirm"><text class="text-base">保存 </text></u-button>
      </view>
    </view>
  </PublicPage>
</template>

<script setup lang="ts">
import { updateUserPwd } from "@/api/login";
import { useUserStore } from "@/stores/user";

const formData = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
})

const rules = reactive({
  oldPassword: {
    type: 'string',
    required: true,
    message: '请输入旧密码',
    trigger: ['blur', 'change']
  },
  newPassword: [
    {
      type: 'string',
      required: true,
      message: '请输入新密码',
      trigger: ['blur', 'change']
    },
    {
      min: 6,
      max: 20,
      message: '密码长度需为6-20位',
      trigger: ['blur', 'change']
    }
  ],
  confirmPassword: [
    {
      type: 'string',
      required: true,
      message: '请再次输入新密码',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule: any, value: string, callback: void) => {
        return value === formData.newPassword
      },
      message: '两次输入的密码不一致',
			trigger: ['blur', 'change']
    }
  ]
})

// 确认修改密码
const _that = getCurrentInstance()
const { logOut } = useUserStore();
const confirm = () => {
  (_that?.refs.form as any).validate().then(() => {
    updateUserPwd(formData).then(res=>{
      uni.showToast({
        title: '修改成功',
        complete: function() {
          setTimeout(() => {
            logOut(`/pages/index/index`);
          }, 1500);
        }
      });
    })
  }).catch((err: any) => {
    uni.showToast({
      title: err[0].message,
      icon: "none"
    });
  });
}




</script>

<style lang="scss" scoped></style>
